// pages/start/start.js
import {
    ajaxPost,
    showToast,
}
from "../../utils/util.js";
import IMController from '../../IMJS/im'
import SDK from "../../IMJS/NIM_Web_SDK_weixin_v6.2.0";
import NetcallController from '../../IMJS/netcall.js'
let app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        canUse: wx.canIUse("button.open-type.getUserInfo"),
        canPhone: wx.canIUse("button.open-type.getPhoneNumber"),
        canPlayer: wx.canIUse('live-player'),
        canPusher: wx.canIUse('live-pusher'),
        show: true,
        type: '', // 分享类型
        hallId: 0, //招聘会id
        hallRoomId: 0, //招聘会聊天室id
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            type,
            hallId,
            hallRoomId,
            companyId,
        } = options
        let that = this
        let token = wx.getStorageSync("token");
        if (type == 'shareHallRoom') {
            this.setData({
                type: type,
                hallId: hallId,
                hallRoomId: hallRoomId
            })
        }
        if (type == 'shareSmall') {
            this.setData({
                type: type,
                hallId: hallId,
                hallRoomId: hallRoomId,
                companyId: companyId,
            })
        }
        if (!token) return;
        wx.getSetting({
            success: res => {
                if (res.authSetting["scope.userInfo"]) {
                    let data = {
                        token: token
                    };
                    ajaxPost("/authuser/myInfo", data, (res) => {
                        if (res.code == 0) {
                            if (res.data.user_info.has_mobile == 0) {
                                showToast('text', '请继续授权,获取手机号');
                                that.setData({
                                    show: false
                                })
                                return;
                            }
                            if (res.data.user_info.type == 4) {
                                return;
                            }
                            that.loginNIM()
                            return;
                        }
                        if (res.code == 40001) {
                            wx.removeStorageSync("token");
                            return;
                        }
                        showToast('text', res.msg, {
                            duration: 3000
                        })

                    });
                }
            }
        });
    },
    /**
     * 获取授权个人信息 ----> 判断是否绑定，如果没有绑定-->绑定手机号
     *               ----> 否则去网易云登录
     */

    getUserInfo: function (e) {
        let that = this;
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            showToast('error', '拒绝授权将会无法使用树枝校招,请重新操作', {
                duration: 3000
            })
            return;
        }
        that.userLogin(e.detail.encryptedData, e.detail.iv)

    },
    userLogin(encryptedData, iv) {
        let that = this
        wx.login({
            success: function (res) {
                let data = {
                    code: res.code, // code  必须给
                    encryptedData: encryptedData, //密文串  必须给
                    iv: iv //加密初始量 必给
                };
                ajaxPost("/login/wxlogin", data, function (res) {
                    if (res.code == 0) {
                        wx.setStorageSync('token', res.data.token);
                        if (res.data.has_mobile == 0) {
                            showToast('text', '请继续授权,获取手机号');
                            that.setData({
                                show: false
                            })
                        } else {
                            that.loginNIM();
                        }
                    } else {
                        showToast('text', res.msg)
                    }
                });

            }
        });
    },
    /**
     * 获取手机号 ---> 网易云登录
     */
    getPhoneNumber(e) {
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            showToast('error', '拒绝授权将会无法使用树枝校招,请重新操作', {
                duration: 3000
            })
            return;
        }
        if (!e.detail.encryptedData) return
        let that = this;
        wx.checkSession({
            success() {
                that.loginPhone(e.detail.encryptedData, e.detail.iv)
            },
            fail() {}
        })
    },

    /**
     * 获取手机号回调
     */

    loginPhone(encryptedData, iv) {
        let that = this;
        let token = wx.getStorageSync("token");
        wx.login({
            success: function (res) {
                let data = {
                    token: token,
                    code: res.code,
                    encryptedData: encryptedData,
                    iv: iv
                };
                ajaxPost("/login/bindmobile", data, function (res) {
                    if (res.code == 0) {
                        that.loginNIM()
                    } else {
                        showToast('text', res.msg)
                    }
                });

            }
        });
    },

    /**
     * 获取网易云账号 ----> 选择角色
     */
    loginNIM() {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
        };
        ajaxPost("/authuser/getwytoken", data, (res) => {
            if (res.code == 0) {
                app.globalData.wytoken = res.data.wytoken
                app.globalData.account = res.data.accid
                wx.showLoading({
                    title: '登录中，请稍等！',
                })
                that.loginWY()
            } else {
                showToast('text', res.msg)
            }
        });
    },

    /**
     * 选择角色   ---- > 进入页面
     */
    setUserType() {
        let data = {
            token: wx.getStorageSync("token"),
            usertype: 3
        };
        ajaxPost("/authuser/usertype", data, res => {
            if (res.code == 0) {
                let {
                    type,
                    hallId,
                    hallRoomId,
                    companyId,
                } = this.data
                if (type == 'shareHallRoom') {
                    wx.redirectTo({
                        url: `/pages/student/hallRoom/hallRoom?id=${hallId}&roomid=${hallRoomId}&type=share`
                    });
                }
                if (type == 'shareSmall') {
                    wx.redirectTo({
                        url: `/pages/student/hallRoom/hallRoom?id=${hallId}&roomid=${hallRoomId}&companyId=${companyId}&type=share`
                    });
                }
            } else {
                showToast('text', res.msg)
            }

        });
    },

    /**
     * 网易登录
     */
    loginWY() {
        console.log('app.globalData.nim', app.globalData.nim);
        console.log('!!app.globalData.nim', !!app.globalData.nim);
        let that = this
        if (!!app.globalData.nim) {
            that.setUserType();
            wx.hideLoading()
            showToast('text', '登录成功')
            return;
        }
        app.globalData.nim = SDK.NIM.getInstance({
            debug: false,
            db: false,
            appKey: app.globalData.appkey,
            token: app.globalData.wytoken,
            account: app.globalData.account,
            promise: true,
            transports: ["websocket"],
            syncSessionUnread: false, // 同步未读数
            onconnect: onConnect,
            onwillreconnect: onWillReconnect,
            ondisconnect: onDisconnect,
            onerror: onError,
        });
        /** 1
         * 连接成功
         */
        function onConnect() {
            // wx.hideLoading()
            that.setUserType();
            wx.hideLoading()
            showToast('text', '登录成功')
            console.error("连接成功");
            app.globalData.netcallController = new NetcallController({
                debug: true,
                nim: app.globalData.nim
            })
        }

        function onWillReconnect(obj) {
            // 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
        }

        function onDisconnect(error) {
            console.log("丢失连接", error);
        }

        function onError(error) {
            showToast('text', '登录失败')
            console.log(" onError", error);
        }

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},

});